package com.tuanzi.loan.business.service.push.impl;

import com.google.common.collect.Lists;
import com.starbaba.model.network.Phead;
import com.tuanzi.loan.business.constants.push.LoanPushMessageSendTaskStatus;
import com.tuanzi.loan.business.constants.push.PushMessageUserGroup;
import com.tuanzi.loan.business.entity.push.LoanPushMessageSendTask;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.repository.push.LoanPushMessageSendTaskRepository;
import com.tuanzi.loan.business.service.push.LoanPushMessageSendTaskService;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.service.CommonServiceImpl;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.family.push.LoanPushMessageSendTaskRequest;
import com.tuanzi.loan.vo.response.family.push.LoanPushMessageSendTaskResponse;
import com.tuanzi.server.loan_base.constant.dictionary.LoanDictionaryCode;
import com.tuanzi.server.loan_base.model.bean.push.PushMessage;
import com.tuanzi.server.loan_base.model.bean.push.PushMessageConfig;
import com.tuanzi.server.loan_base.model.response.commom.Result;
import com.tuanzi.server.loan_base.model.response.commom.ResultUtils;
import com.tuanzi.server.loan_base.util.push.PushMessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: chenweijun
 * @Date: 2018/12/12 14:36
 * @Description:
 */
@Debug
@Slf4j
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class LoanPushMessageSendTaskServiceImpl extends CommonServiceImpl<LoanPushMessageSendTask, Long> implements LoanPushMessageSendTaskService{

    @Autowired
    private LoanPushMessageSendTaskRepository loanPushMessageSendTaskRepository;

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    protected JpaRepository<LoanPushMessageSendTask, Long> getRepository() {
        return loanPushMessageSendTaskRepository;
    }


    @Override
    public Page<LoanPushMessageSendTaskResponse> list(PageSearcher<LoanPushMessageSendTaskRequest> pageSearcher) {
        return loanPushMessageSendTaskRepository.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
    }

    @Override
    public Long countByStatus(LoanPushMessageSendTaskStatus status) {
        return loanPushMessageSendTaskRepository.countByStatus(status);
    }

    @Override
    public LoanPushMessageSendTask findTopByStatusAndSendTimeBefore(LoanPushMessageSendTaskStatus status, Date sendTime) {
        return loanPushMessageSendTaskRepository.findTopByStatusAndSendTimeBefore(status, sendTime);
    }

    @Override
    public void updateStatusWithoutTransactional(LoanPushMessageSendTask sendTask, LoanPushMessageSendTaskStatus status) {
        sendTask.setStatus(status);
        loanPushMessageSendTaskRepository.save(sendTask);
    }

    @Override
    public void cancelTask(Long id) {
        LoanPushMessageSendTask sendTask = loanPushMessageSendTaskRepository.findOne(id);
        sendTask.setStatus(LoanPushMessageSendTaskStatus.SEND_CANCEL);
        loanPushMessageSendTaskRepository.save(sendTask);
    }

    @Override
    public void onResend(Long id) {
        LoanPushMessageSendTask sendTask = loanPushMessageSendTaskRepository.findOne(id);
        sendTask.setStatus(LoanPushMessageSendTaskStatus.READY_SEND);
        loanPushMessageSendTaskRepository.save(sendTask);
    }

    @Override
    public void sendPushMessage(LoanPushMessageSendTask sendTask) {

        try {

            List<Result> results = Lists.newArrayList();
            if(sendTask.getUserGroup().equals(PushMessageUserGroup.APP)){  //针对APP全量推送

//                PushMessage pushMessage = GsonUtils.toObject(sendTask.getMessage(), PushMessage.class);
//                Lists.newArrayList(StringUtils.split(sendTask.getProductId(), ",")).stream().forEach(x ->{
//
//                    Dictionary dictionary = dictionaryService.findByCodeAndValue1(LoanDictionaryCode.PUSH_MESSAGE_CONFIG, x);
//
//                    PushMessageConfig config = new PushMessageConfig();
//                    config.setAppId(dictionary.getValue2());
//                    config.setAppKey(dictionary.getValue3());
//                    config.setMasterSecret(dictionary.getValue4());
//
//
//                    Result result = PushMessageUtils.pushMessageToAPP(config, x, "ios", pushMessage);
//                    results.add(result);
//                });


                results.add(ResultUtils.success());
                results.add(ResultUtils.success());
                results.add(ResultUtils.success());
                PushMessage pushMessage = GsonUtils.toObject(sendTask.getMessage(), PushMessage.class);
            }


            if(results.stream().allMatch(x -> ResultUtils.isSuccess(x))){
                sendTask.setStatus(LoanPushMessageSendTaskStatus.SEND_DONE);
            }else{
                sendTask.setStatus(LoanPushMessageSendTaskStatus.SEND_FAIL);
            }
            sendTask.setFinishTime(new Date());
        }catch (Throwable e){
            log.error(e.getMessage(), e);
            sendTask.setStatus(LoanPushMessageSendTaskStatus.SEND_FAIL);
        }finally {
            loanPushMessageSendTaskRepository.save(sendTask);
        }
    }

}
